package net.neiquan.applibrary.wight;

import android.animation.LayoutTransition;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.sendtion.xrichtext.DataImageView;
import com.sendtion.xrichtext.GlideApp;
import com.sendtion.xrichtext.RichTextEditor;

import net.neiquan.applibrary.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：dyj
 * 时间：2019/11/8
 */

@SuppressLint({"NewApi", "InflateParams"})
public class KeyRichTextEditor extends ScrollView {
    public Activity activity;
    public static final int EDIT_PADDING = 10;
    public int viewTagIndex;
    public LinearLayout allLayout;
    public LayoutInflater inflater;
    public OnKeyListener keyListener;
    public OnClickListener btnListener;
    public OnFocusChangeListener focusListener;
    public TextWatcher textWatcher;
    public MsgEditText lastFocusEdit;
    public LayoutTransition mTransitioner;
    public int editNormalPadding;
    public int disappearingImageIndex;
    public ArrayList<String> imagePaths;
    public int rtImageHeight;
    public int rtImageBottom;
    public String rtTextInitHint;
    public int rtTextSize;
    public int rtTextColor;
    public int rtTextLineSpace;
    public RichTextEditor.OnRtImageDeleteListener onRtImageDeleteListener;
    public RichTextEditor.OnRtImageClickListener onRtImageClickListener;

    public KeyRichTextEditor(Context context) {
        this(context, (AttributeSet)null);
    }

    public KeyRichTextEditor(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public KeyRichTextEditor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.viewTagIndex = 1;
        this.editNormalPadding = 0;
        this.disappearingImageIndex = 0;
        this.rtImageHeight = 500;
        this.rtImageBottom = 10;
        this.rtTextInitHint = "请输入内容";
        this.rtTextSize = 16;
        this.rtTextColor = Color.parseColor("#757575");
        this.rtTextLineSpace = 8;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RichTextEditor);
        this.rtImageHeight = ta.getInteger(R.styleable.RichTextEditor_rt_editor_image_height, 500);
        this.rtImageBottom = ta.getInteger(R.styleable.RichTextEditor_rt_editor_image_bottom, 10);
        this.rtTextSize = ta.getDimensionPixelSize(R.styleable.RichTextEditor_rt_editor_text_size, 16);
        this.rtTextLineSpace = ta.getDimensionPixelSize(R.styleable.RichTextEditor_rt_editor_text_line_space, 8);
        this.rtTextColor = ta.getColor(R.styleable.RichTextEditor_rt_editor_text_color, Color.parseColor("#757575"));
        this.rtTextInitHint = ta.getString(R.styleable.RichTextEditor_rt_editor_text_init_hint);
        ta.recycle();
        this.activity = (Activity)context;
        this.imagePaths = new ArrayList();
        this.inflater = LayoutInflater.from(context);
        this.allLayout = new LinearLayout(context);
        this.allLayout.setOrientation(LinearLayout.VERTICAL);
        this.setupLayoutTransitions();
        LayoutParams layoutParams = new LayoutParams(-1, -2);
        this.allLayout.setPadding(50, 15, 50, 15);
        this.addView(this.allLayout, layoutParams);
        this.keyListener = new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == 0 && event.getKeyCode() == 67) {
                    MsgEditText edit = (MsgEditText)v;
                    KeyRichTextEditor.this.onBackspacePress(edit);
                }

                return false;
            }
        };
        this.btnListener = new OnClickListener() {
            public void onClick(View v) {
                if (v instanceof DataImageView) {
                    DataImageView imageView = (DataImageView)v;
                    if (KeyRichTextEditor.this.onRtImageClickListener != null) {
                        KeyRichTextEditor.this.onRtImageClickListener.onRtImageClick(imageView.getAbsolutePath());
                    }
                } else if (v instanceof ImageView) {
                    RelativeLayout parentView = (RelativeLayout)v.getParent();
                    KeyRichTextEditor.this.onImageCloseClick(parentView);
                }

            }
        };
        this.focusListener = new OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    KeyRichTextEditor.this.lastFocusEdit = (MsgEditText)v;
                }

            }
        };
        this.textWatcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
                //向前删除一个字符，@后的内容必须大于一个字符，可以在后面加一个空格
                if (lengthBefore == 1 && lengthAfter == 0) {
                    MsgEditText.MyTextSpan[] spans = lastFocusEdit.getText().getSpans(0, lastFocusEdit.getText().length(), MsgEditText.MyTextSpan.class);
                    for (MsgEditText.MyTextSpan myImageSpan : spans) {
                        if (lastFocusEdit.getText().getSpanEnd(myImageSpan) == start && !text.toString().endsWith(myImageSpan.getShowText())) {
                            lastFocusEdit.getText().delete(lastFocusEdit.getText().getSpanStart(myImageSpan), lastFocusEdit.getText().getSpanEnd(myImageSpan));
                            break;
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(-1, -1);
        MsgEditText firstEdit = this.createEditText(this.rtTextInitHint, this.dip2px(context, 10.0F));
//        MsgEditText firstEdit = this.createEditText(this.rtTextInitHint, 0);
        this.allLayout.addView(firstEdit, firstEditParam);
        this.lastFocusEdit = firstEdit;
    }

    public int dip2px(Context context, float dipValue) {
        float m = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue * m + 0.5F);
    }

    public void onBackspacePress(MsgEditText editTxt) {
        int startSelection = editTxt.getSelectionStart();
        if (startSelection == 0) {
            int editIndex = this.allLayout.indexOfChild(editTxt);
            View preView = this.allLayout.getChildAt(editIndex - 1);
            if (null != preView) {
                if (preView instanceof RelativeLayout) {
                    this.onImageCloseClick(preView);
                } else if (preView instanceof MsgEditText) {
                    String str1 = editTxt.getText().toString();
                    MsgEditText preEdit = (MsgEditText)preView;
                    String str2 = preEdit.getText().toString();
                    this.allLayout.setLayoutTransition((LayoutTransition)null);
                    this.allLayout.removeView(editTxt);
                    this.allLayout.setLayoutTransition(this.mTransitioner);
                    preEdit.setText(str2 + str1);
                    preEdit.requestFocus();
                    preEdit.setSelection(str2.length(), str2.length());
                    this.lastFocusEdit = preEdit;
                }
            }
        }

    }

    public void setOnRtImageDeleteListener(com.sendtion.xrichtext.RichTextEditor.OnRtImageDeleteListener onRtImageDeleteListener) {
        this.onRtImageDeleteListener = onRtImageDeleteListener;
    }

    public void setOnRtImageClickListener(com.sendtion.xrichtext.RichTextEditor.OnRtImageClickListener onRtImageClickListener) {
        this.onRtImageClickListener = onRtImageClickListener;
    }

    public void onImageCloseClick(View view) {
        if (!this.mTransitioner.isRunning()) {
            this.disappearingImageIndex = this.allLayout.indexOfChild(view);
            List<EditData> dataList = this.buildEditData();
            KeyRichTextEditor.EditData editData = (KeyRichTextEditor.EditData)dataList.get(this.disappearingImageIndex);
            if (editData.imagePath != null) {
                if (this.onRtImageDeleteListener != null) {
                    this.onRtImageDeleteListener.onRtImageDelete(editData.imagePath);
                }

                this.imagePaths.remove(editData.imagePath);
            }

            this.allLayout.removeView(view);
            this.mergeEditText();
        }

    }

    public void onImageClick(DataImageView imageView) {
    }

    public void clearAllLayout() {
        this.allLayout.removeAllViews();
    }

    public int getLastIndex() {
        int lastEditIndex = this.allLayout.getChildCount();
        return lastEditIndex;
    }

    public MsgEditText createEditText(String hint, int paddingTop) {
        MsgEditText editText = (MsgEditText)this.inflater.inflate(R.layout.rich_edittext1, (ViewGroup)null);
        editText.setOnKeyListener(this.keyListener);
        editText.setTag(this.viewTagIndex++);
        editText.setPadding(this.editNormalPadding, paddingTop, this.editNormalPadding, paddingTop);
        editText.setHint(hint);
        editText.setTextSize(0, (float)this.rtTextSize);
        editText.setTextColor(this.rtTextColor);
        editText.setLineSpacing((float)this.rtTextLineSpace, 1.0F);
        editText.setOnFocusChangeListener(this.focusListener);
        editText.addTextChangedListener(textWatcher);
        return editText;
    }

    public RelativeLayout createImageLayout() {
        RelativeLayout layout = (RelativeLayout)this.inflater.inflate(com.sendtion.xrichtext.R.layout.edit_imageview, (ViewGroup)null);
        layout.setTag(this.viewTagIndex++);
        View closeView = layout.findViewById(R.id.image_close);
        closeView.setTag(layout.getTag());
        closeView.setOnClickListener(this.btnListener);
        DataImageView imageView = (DataImageView)layout.findViewById(R.id.edit_imageView);
        imageView.setOnClickListener(this.btnListener);
        return layout;
    }

    public void insertImage(String imagePath, int width) {
        Bitmap bmp = this.getScaledBitmap(imagePath, width);
        this.insertImage(bmp, imagePath);
    }

    public void insertImage(Bitmap bitmap, String imagePath) {
        String lastEditStr = this.lastFocusEdit.getText().toString();
        int cursorIndex = this.lastFocusEdit.getSelectionStart();
        String editStr1 = lastEditStr.substring(0, cursorIndex).trim();
        String editStr2 = lastEditStr.substring(cursorIndex).trim();
        int lastEditIndex = this.allLayout.indexOfChild(this.lastFocusEdit);
        if (lastEditStr.length() == 0) {
            this.addEditTextAtIndex(lastEditIndex + 1, "");
            this.addImageViewAtIndex(lastEditIndex + 1, bitmap, imagePath);
        } else if (editStr1.length() == 0) {
            this.addImageViewAtIndex(lastEditIndex, bitmap, imagePath);
            this.addEditTextAtIndex(lastEditIndex + 1, "");
        } else if (editStr2.length() == 0) {
            this.addEditTextAtIndex(lastEditIndex + 1, "");
            this.addImageViewAtIndex(lastEditIndex + 1, bitmap, imagePath);
        } else {
            this.lastFocusEdit.setText(editStr1);
            this.addEditTextAtIndex(lastEditIndex + 1, editStr2);
            this.addEditTextAtIndex(lastEditIndex + 1, "");
            this.addImageViewAtIndex(lastEditIndex + 1, bitmap, imagePath);
        }

        this.hideKeyBoard();
    }

    public void hideKeyBoard() {
        InputMethodManager imm = (InputMethodManager)this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && this.lastFocusEdit != null) {
            imm.hideSoftInputFromWindow(this.lastFocusEdit.getWindowToken(), 0);
        }

    }

    public void addEditTextAtIndex(int index, CharSequence editStr) {
//        EditText editText2 = this.createEditText("插入文字", 10);
        MsgEditText editText2 = this.createEditText("插入文字", 0);
        if (editStr != null && editStr.length() > 0) {
            editText2.setText(editStr);
        }

        editText2.setOnFocusChangeListener(this.focusListener);
        this.allLayout.setLayoutTransition((LayoutTransition)null);
        this.allLayout.addView(editText2, index);
        this.allLayout.setLayoutTransition(this.mTransitioner);
        this.lastFocusEdit = editText2;
        this.lastFocusEdit.requestFocus();
        this.lastFocusEdit.setSelection(editStr.length(), editStr.length());
    }

    public void addImageViewAtIndex(int index, Bitmap bmp, String imagePath) {
        this.imagePaths.add(imagePath);
        RelativeLayout imageLayout = this.createImageLayout();
        DataImageView imageView = (DataImageView)imageLayout.findViewById(R.id.edit_imageView);
        GlideApp.with(this.getContext()).load(imagePath).centerCrop().into(imageView);
        imageView.setAbsolutePath(imagePath);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        int imageHeight;
        if (this.rtImageHeight > 0) {
            imageHeight = this.rtImageHeight;
        } else {
            imageHeight = this.allLayout.getWidth() * bmp.getHeight() / bmp.getWidth();
        }

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, imageHeight);
        lp.bottomMargin = this.rtImageBottom;
        imageView.setLayoutParams(lp);
        if (this.rtImageHeight > 0) {
            GlideApp.with(this.getContext()).load(imagePath).centerCrop().placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(imageView);
        } else {
            GlideApp.with(this.getContext()).load(imagePath).placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(imageView);
        }

        this.allLayout.addView(imageLayout, index);
    }

    public void addImageViewAtIndex(int index, String imagePath) {
        this.imagePaths.add(imagePath);
        RelativeLayout imageLayout = this.createImageLayout();
        DataImageView imageView = (DataImageView)imageLayout.findViewById(R.id.edit_imageView);
        imageView.setAbsolutePath(imagePath);
        int imageHeight;
        if (this.rtImageHeight > 0) {
            imageHeight = this.rtImageHeight;
        } else {
            Bitmap bmp = BitmapFactory.decodeFile(imagePath);
            imageHeight = this.allLayout.getWidth() * bmp.getHeight() / bmp.getWidth();
        }

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, imageHeight);
        lp.bottomMargin = this.rtImageBottom;
        imageView.setLayoutParams(lp);
        if (this.rtImageHeight > 0) {
            GlideApp.with(this.getContext()).load(imagePath).centerCrop().placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(imageView);
        } else {
            GlideApp.with(this.getContext()).load(imagePath).placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(imageView);
        }

        this.allLayout.addView(imageLayout, index);
    }

    public Bitmap getScaledBitmap(String filePath, int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int sampleSize = options.outWidth > width ? options.outWidth / width + 1 : 1;
        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public void setupLayoutTransitions() {
        this.mTransitioner = new LayoutTransition();
        this.allLayout.setLayoutTransition(this.mTransitioner);
        this.mTransitioner.addTransitionListener(new LayoutTransition.TransitionListener() {
            public void startTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
            }

            public void endTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
                if (!transition.isRunning() && transitionType == 1) {
                    KeyRichTextEditor.this.mergeEditText();
                }

            }
        });
        this.mTransitioner.setDuration(300L);
    }

    public void mergeEditText() {
        View preView = this.allLayout.getChildAt(this.disappearingImageIndex - 1);
        View nextView = this.allLayout.getChildAt(this.disappearingImageIndex);
        if (preView != null && preView instanceof MsgEditText && null != nextView && nextView instanceof MsgEditText) {
            Log.d("LeiTest", "合并EditText");
            MsgEditText preEdit = (MsgEditText)preView;
            MsgEditText nextEdit = (MsgEditText)nextView;
            String str1 = preEdit.getText().toString();
            String str2 = nextEdit.getText().toString();
            String mergeText = "";
            if (str2.length() > 0) {
                mergeText = str1 + "\n" + str2;
            } else {
                mergeText = str1;
            }

            this.allLayout.setLayoutTransition((LayoutTransition)null);
            this.allLayout.removeView(nextEdit);
            preEdit.setText(mergeText);
            preEdit.requestFocus();
            preEdit.setSelection(str1.length(), str1.length());
            this.allLayout.setLayoutTransition(this.mTransitioner);
        }

    }

    public List<EditData> buildEditData() {
        List<EditData> dataList = new ArrayList();
        int num = this.allLayout.getChildCount();

        for(int index = 0; index < num; ++index) {
            View itemView = this.allLayout.getChildAt(index);
            KeyRichTextEditor.EditData itemData = new KeyRichTextEditor.EditData();
            if (itemView instanceof MsgEditText) {
                MsgEditText item = (MsgEditText)itemView;
                itemData.inputStr = item.getText().toString();
                itemData.mask=item.getMaskString();
                itemData.name=item.getUserNameString();
                itemData.userId=item.getUserIdString();
            } else if (itemView instanceof RelativeLayout) {
                DataImageView item = (DataImageView)itemView.findViewById(R.id.edit_imageView);
                itemData.imagePath = item.getAbsolutePath();
            }

            dataList.add(itemData);
        }

        return dataList;
    }

    public int getRtImageHeight() {
        return this.rtImageHeight;
    }

    public void setRtImageHeight(int rtImageHeight) {
        this.rtImageHeight = rtImageHeight;
    }

    public int getRtImageBottom() {
        return this.rtImageBottom;
    }

    public void setRtImageBottom(int rtImageBottom) {
        this.rtImageBottom = rtImageBottom;
    }

    public String getRtTextInitHint() {
        return this.rtTextInitHint;
    }

    public void setRtTextInitHint(String rtTextInitHint) {
        this.rtTextInitHint = rtTextInitHint;
    }

    public int getRtTextSize() {
        return this.rtTextSize;
    }

    public void setRtTextSize(int rtTextSize) {
        this.rtTextSize = rtTextSize;
    }

    public int getRtTextColor() {
        return this.rtTextColor;
    }

    public void setRtTextColor(int rtTextColor) {
        this.rtTextColor = rtTextColor;
    }

    public int getRtTextLineSpace() {
        return this.rtTextLineSpace;
    }

    public void setRtTextLineSpace(int rtTextLineSpace) {
        this.rtTextLineSpace = rtTextLineSpace;
    }

    public class EditData {
        public String inputStr;
        public String imagePath;
        public Bitmap bitmap;
        public String name;
        public String userId;
        public String mask;

        public EditData() {
//            getMaskString();
//            getUserIdString();
//            getUserNameString();
        }

//        //获取用户Id列表
//        public void getUserIdString() {
//            KeyWordEditText.MyTextSpan[] spans = lastFocusEdit.getText().getSpans(0, lastFocusEdit.getText().length(), KeyWordEditText.MyTextSpan.class);
//            StringBuilder builder = new StringBuilder();
//            for (KeyWordEditText.MyTextSpan myTextSpan : spans) {
//                String realText = lastFocusEdit.getText().toString().substring(lastFocusEdit.getText().getSpanStart(myTextSpan), lastFocusEdit.getText().getSpanEnd(myTextSpan));
//                String showText = myTextSpan.getShowText();
//                if (realText.equals(showText)) {
//                    builder.append(myTextSpan.getUserId()).append(",");
//                }
//            }
//            if (!TextUtils.isEmpty(builder.toString())) {
//                builder.deleteCharAt(builder.length() - 1);
//            }
//            userId= builder.toString();
//        }
//
//        public void getMaskString() {
//            KeyWordEditText.MyTextSpan[] spans = lastFocusEdit.getText().getSpans(0, lastFocusEdit.getText().length(), KeyWordEditText.MyTextSpan.class);
//            StringBuilder builder = new StringBuilder();
//            for (KeyWordEditText.MyTextSpan myTextSpan : spans) {
//                String realText = lastFocusEdit.getText().toString().substring(lastFocusEdit.getText().getSpanStart(myTextSpan), lastFocusEdit.getText().getSpanEnd(myTextSpan));
//                String showText = myTextSpan.getShowText();
//                if (realText.equals(showText)) {
//                    builder.append(myTextSpan.getMaskText()).append(",");
//                }
//            }
//            if (!TextUtils.isEmpty(builder.toString())) {
//                builder.deleteCharAt(builder.length() - 1);
//            }
//            mask= builder.toString();
//        }
//
//
//        public void getUserNameString() {
//            KeyWordEditText.MyTextSpan[] spans = lastFocusEdit.getText().getSpans(0, lastFocusEdit.getText().length(), KeyWordEditText.MyTextSpan.class);
//            StringBuilder builder = new StringBuilder();
//            for (KeyWordEditText.MyTextSpan myTextSpan : spans) {
//                String realText = lastFocusEdit.getText().toString().substring(lastFocusEdit.getText().getSpanStart(myTextSpan), lastFocusEdit.getText().getSpanEnd(myTextSpan));
//                String showText = myTextSpan.getShowText();
//                if (realText.equals(showText)) {
//                    builder.append(myTextSpan.getShowText()).append(",");
//                }
//            }
//            if (!TextUtils.isEmpty(builder.toString())) {
//                builder.deleteCharAt(builder.length() - 1);
//            }
//            name= builder.toString();
//        }

    }

    public interface OnRtImageClickListener {
        void onRtImageClick(String var1);
    }

    public interface OnRtImageDeleteListener {
        void onRtImageDelete(String var1);
    }
}
